//
//  WKPhotoManager.swift
//  NewDelivery
//
//  Created by 天下宅 on 2016/11/8.
//  Copyright © 2016年 天下宅. All rights reserved.
//

import Foundation
import UIKit
import Photos

let WKAlbumName = "宅天下"
//为一个输入参数为UIView无返回值的函数
public typealias photosBlock = ([UIImage]) -> ()
public typealias takePhotoBlock = (UIImage) -> ()

class WKPhotoManager: NSObject {
    
    var imageSize = CGSize.init(width: 200, height: 200)
    var currentAlbumIndex = 0
    
    var photoOptions:PHFetchOptions = PHFetchOptions()
    
    
    private let imageManager = PHImageManager.default()
    private var hasWKAlbum = false
    
    private var imagesDict = [String:UIImage]()
    private var sourceImages = [UIImage]()
    private var albumNames = [String]()
    private var albums = NSMutableArray()
    private var collections = NSMutableArray()


    static let shared:WKPhotoManager =
    {
        let instance = WKPhotoManager()
        instance.photoOptions.sortDescriptors = [NSSortDescriptor.init(key: "creationDate", ascending: false)]
        instance.getAllPhotoData()
        return instance
    }()
    
    func getAllPhotoData() {
        
        self.albums.removeAllObjects()
        self.albumNames.removeAll()
        self.collections.removeAllObjects()
        
        
        let allPhotos = PHAsset.fetchAssets(with: photoOptions)
        self.albums.add(allPhotos)
        self.albumNames.append("所有照片")
        
        let sAlubms = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumRegular, options: nil)
        for i in 0..<sAlubms.count {
            let collection = sAlubms[i]
            if collection.isKind(of: PHAssetCollection.classForCoder())
            {
                if collection.localizedTitle == WKAlbumName
                {
                    hasWKAlbum = true
                    collections.insert(collection, at: 0)
                }
                let fetchResult = PHAsset.fetchAssets(in: collection, options: photoOptions)
                self.albumNames.append(collection.localizedTitle!)
                self.albums.add(fetchResult)
                self.collections.add(collection)
            }
        }
        
        if !hasWKAlbum
        {
            self.creatWKAlubm()
        }
    }
    
    private func creatWKAlubm()//创建相册
    {
        PHPhotoLibrary.shared().performChanges({ 
            let a = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: WKAlbumName)
            }) { (success, error) in
                if success{
                    print("创建成功")
                    self.hasWKAlbum = true
                }
                else
                {
                    print("创建失败" + (error?.localizedDescription)!)
                }
        }
    }
    
    
    func getSourceImage(WithImage image:UIImage,block: @escaping takePhotoBlock)  {
        

        let options = PHImageRequestOptions()
        options.isSynchronous = true//只获得一张（返回一次），同一张图片会存放在多个相册中~ 可能会返回多次
        
        if let asset = PHAsset.fetchAssets(withLocalIdentifiers: [image.wk_assetID], options: nil).lastObject
        {
            //获得原图
            PHImageManager.default().requestImage(for: asset, targetSize: CGSize.init(width: asset.pixelWidth, height: asset.pixelHeight), contentMode: .default, options: options, resultHandler: { (img, info) in
                block(img!)
            })
        }
        else
        {
            print("无效的assetID")
        }

        

    }
    
    //保存相片
    func sava(image:UIImage, block: @escaping takePhotoBlock)
    {
        let stats = PHPhotoLibrary.authorizationStatus()
        switch stats {
        case .denied,.restricted:
            print("前往设置更改")
        default:
            var assetID = ""
            PHPhotoLibrary.shared().performChanges({ 
                if #available(iOS 9.0, *) {
                    assetID = PHAssetCreationRequest.creationRequestForAsset(from: image).placeholderForCreatedAsset?.localIdentifier ?? ""
                } else {
                   assetID = PHAssetChangeRequest.creationRequestForAsset(from: image).placeholderForCreatedAsset?.localIdentifier ?? ""
                }
            }, completionHandler: { (success, error) in
                if success
                {
                    let asset = PHAsset.fetchAssets(withLocalIdentifiers: [assetID], options: nil).lastObject
                    print(asset?.localIdentifier ?? "什么都没有")
                    print(assetID)
                    image.wk_assetID = assetID
                    image.wk_index = "1"
                    let collection = self.collections[self.currentAlbumIndex]
                    PHPhotoLibrary.shared().performChanges({ 
                        PHAssetCollectionChangeRequest.init(for: collection as! PHAssetCollection)!.addAssets([asset!] as NSFastEnumeration)
                    }, completionHandler: { (success, error) in
                        if success
                        {
                            print("成功")
                            block(image)
                        }
                        else
                        {
                            print("失败\(error?.localizedDescription)")
                        }
                    })
                    
                }
            })
        }
        
    }
    
    
    func refreshData(WithBlock block:@escaping photosBlock)
    {
        DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async {
            self.getAllPhotoData()
            self.imagesDict.removeAll()
            self.sourceImages.removeAll()
            
            let r = self.albums[self.currentAlbumIndex] as! PHFetchResult<PHAsset>
            
            
            
            
            for i in 0..<r.count
            {
                let asset = r[i]
                
                let imageRequest_Option = PHImageRequestOptions.init()
                imageRequest_Option.deliveryMode = .highQualityFormat
                imageRequest_Option.isNetworkAccessAllowed = false
                imageRequest_Option.isSynchronous = true

                self.imageManager.requestImage(for: asset, targetSize: self.imageSize, contentMode: .aspectFit, options: imageRequest_Option, resultHandler: { (image, dict) in
                    
                    if image != nil
                    {
                        image?.wk_assetID = asset.localIdentifier
                        let key = "\(i)"
                        self.imagesDict[key] = image
                        self.sourceImages.append(image!)
                    }
                })
            }
            
            DispatchQueue.main.async {
                block(self.sourceImages)
            }
        }
    }
}
